//
//  PostViewController.m
//  HeSaid
//
//  Created by MWJ on 15/5/4.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "PostViewController.h"
#import "AppDelegate.h"
#import "ViewController.h"
#import "ASIFormDataRequest.h"
#define postURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/post"
#define integralURL  @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/postuser"
#define identificationURL  @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/postId"
@interface PostViewController (){
    AppDelegate *app;
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    NSString *string1;
    NSString *str2;
    NSString *str1;
    UIAlertView *_alert;
    NSString *currentTime;
    UIPickerView *timePicker;
    NSMutableArray *timeArray;
    UILabel *myView;
    int setUpStr;  //设置 状态
    NSString *integral;
    NSString *integralStr;
    NSString *jd;
    NSString *wd;
    NSDictionary *roud;
    UIButton *doneButton;
    int keyboard;
}

@end

@implementation PostViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"发帖子";
    [self.set.layer setMasksToBounds:YES];
    [self.set.layer setCornerRadius:5.0];
    [self.submitbutton.layer setMasksToBounds:YES];
    [self.submitbutton.layer setCornerRadius:5.0];
    //征文框的外观
    self.content.layer.cornerRadius = 8;
    self.content.layer.borderColor = [UIColor grayColor].CGColor;
    self.content.layer.borderWidth = 0.5;
    
    [self.slider addTarget:self action:@selector(change) forControlEvents:UIControlEventValueChanged];
    //为slider添加方法当slider的值改变时就会触发change方法
    self.slider.continuous = NO;
    
    //帖子显示时长数组，1～10分钟
    timeArray= [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil];
    
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    [self positioning];
    
    //“设置”按钮的状态
    setUpStr = 0;
    
    //时间选择器
    timePicker=[[UIPickerView alloc]initWithFrame:CGRectMake(0,340, [UIScreen mainScreen].bounds.size.width, 200)];
    [timePicker setBackgroundColor:[UIColor whiteColor]];
    timePicker.delegate=self;
    timePicker.dataSource=self;
    timePicker.hidden = YES;
    [self.view addSubview:timePicker];
    
    //帖子默认显示时间为 10 分钟
    self.ShowTime.text = @"5";
    doneButton =  [[UIButton alloc]init];
    [doneButton setBackgroundImage:[UIImage imageNamed:@"done.png"] forState:UIControlStateNormal];
//    [doneButton setTitle:@"done" forState: UIControlStateNormal];
//    [doneButton setTintColor:[UIColor whiteColor]];
//    doneButton.backgroundColor = [UIColor brownColor];
    [doneButton addTarget: self action:@selector(hideKeyboard) forControlEvents: UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (doneButtonshow:) name: UIKeyboardDidShowNotification object:nil];
    
}
-(void) doneButtonshow: (NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    keyboard = keyboardRect.size.height;
    doneButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-30, [UIScreen mainScreen].bounds.size.height-(keyboard+85), 30, 20);
    [self.view addSubview:doneButton];
}
-(void) hideKeyboard {
    [doneButton removeFromSuperview];
    [self.content resignFirstResponder];
}
-(void)change{
    NSString *a = [NSString stringWithFormat:@"%f",self.slider.value*10];
    self.ShowTime.text =[NSString stringWithFormat:@"%d",[a intValue]];
}

#pragma mark - pickView的组建数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 1;     //这个picker里的组键数
    
}

#pragma mark - pickView的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return 10;
}

#pragma mark - pickView的内容
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    myView = nil;
    myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
    
    myView.textAlignment = NSTextAlignmentCenter;
    
    myView.text = [NSString stringWithFormat:@"%@ 分钟",[timeArray objectAtIndex:row]];
    
    myView.font = [UIFont systemFontOfSize:25];         //用label来设置字体大小
    
    myView.backgroundColor = [UIColor clearColor];
    
    
    return myView;
}

#pragma mark - pickView内容变动
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    self.ShowTime.text = timeArray[row];
}
#pragma mark - pickView每行的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    return 30;
}

#pragma mark - pickView每行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 30.0;
}


#pragma mark - 定位
-(void)positioning{
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
    //开始定位
    [locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code==kCLErrorLocationUnknown) {
        NSLog(@"无法获取到当前位置信息");
    }else if (error.code==kCLErrorNetwork){
        NSLog(@"网络异常");
    }else if (error.code==kCLErrorDenied){
        NSLog(@"您的phone禁用获取位置服务");
    }
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取位置信息失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLLocation *currentLocation=newLocation;
    NSString *locstr1 = @"http://restapi.amap.com/v3/assistant/coordinate/convert?locations=";
    NSString *locstr2 = [NSString stringWithFormat:@"%f,%f",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude];
    NSString *locstr3 = @"&coordsys=gps&output=json&key=b1ba3d04de3c8efdc866712f66033064";
    NSString *locstr4 = [NSString stringWithFormat:@"%@%@%@",locstr1,locstr2,locstr3];
    NSURL *url=[NSURL URLWithString:locstr4];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSString *poststr =@"";
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        roud = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:roud waitUntilDone:YES];
        NSArray *strarray = [roud[@"locations"] componentsSeparatedByString:@","];
        _longitude = [strarray[0] doubleValue];
        _latitude = [strarray[1] doubleValue];
    if (currentLocation!=nil) {
        //停止获取地址位置
        [locationManager stopUpdatingLocation];
        //转换地址
        [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            if (error==nil&&[placemarks count]>0) {
                Placemark=[placemarks lastObject];
                NSString *s1=[[NSString alloc]init];
                //地标的名字
                s1=[NSString stringWithFormat:@"%@",Placemark.name];
            }else{
                UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [Alert show];
            }
        }];
    }
    }];
}
-(void)refreshData{
    
}
#pragma mark - 自动获取当时时间

-(void)getTime{
    NSDateFormatter *fomatter=[[NSDateFormatter alloc]init];
    [fomatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowTime=[fomatter stringFromDate:[NSDate date]];
    currentTime=nowTime;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - “发布”按钮点击
- (IBAction)published:(id)sender {
    if (self.content.text.length<12) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"帖子内容少于十二个字，发送失败！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
<<<<<<< HEAD
        //获取当下发帖的时间
        [self getTime];
        jd = [NSString stringWithFormat:@"%f",_longitude];
        wd = [NSString stringWithFormat:@"%f",_latitude];
=======
    //获取当下发帖的时间
    [self getTime];
    jd = [NSString stringWithFormat:@"%f",_longitude];
    wd = [NSString stringWithFormat:@"%f",_latitude];
>>>>>>> 4b04801d95a25eb22fcb8820da68a35773c3052f
        if ([jd isEqualToString:@"0.000000"]||[wd isEqualToString:@"0.000000"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位失败，请检查您的JPS是否已经打开！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
<<<<<<< HEAD
            NSString *poststr =[NSString stringWithFormat:@"message_content=%@&message_time=%@&user_id=%@&message_longitude=%@&message_latitude=%@&message_showtime=%@",self.content.text,currentTime,app.user_id,jd,wd,self.ShowTime.text];
            [self londingPath:postURL Str:poststr];
=======
    NSString *poststr =[NSString stringWithFormat:@"message_content=%@&message_time=%@&user_id=%@&message_longitude=%@&message_latitude=%@&message_showtime=%@",self.content.text,currentTime,app.user_id,jd,wd,self.ShowTime.text];
    [self londingPath:postURL Str:poststr];
>>>>>>> 4b04801d95a25eb22fcb8820da68a35773c3052f
        }
    }

}
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    string1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:string1 waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
    int intstr = [string1 intValue];
    if ([self.content.text isEqualToString:@""]||[self.ShowTime.text isEqualToString:@""]||[jd isEqualToString:@""]||[wd isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"失败" message:@"请发表完整帖子信息" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    else{
        if (intstr == 1 ) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"发表成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            _alert=alert;
            [alert show];
            
            //发表成功之后 积分数 ＋5 之后上传数据库
            integral=[NSString stringWithFormat:@"%d",([app.integralCount intValue]+5)];
            NSString *poststr1 =[NSString stringWithFormat:@"user_id=%@&user_count=%d",app.user_id,[integral intValue]];
            [self londingPath1:integralURL Str1:poststr1];
            NSString *poststr2 =[NSString stringWithFormat:@"user_id=%@&",app.user_id];
            [self londingPath2:identificationURL Str2:poststr2];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"发表失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }
}
-(void)londingPath2:(NSString *)path Str2:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        str2 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData2:) withObject:str2 waitUntilDone:YES];
    }];
}
-(void)refreshData2:(NSMutableArray *)sender2{
}
#pragma mark - 发表成功之后积分数＋5后上传
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        integralStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:integralStr waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender1{
    }
#pragma mark - 提示框“确定”事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        //跳转到主页
        ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"viewVC"];
        [self.navigationController pushViewController:vc animated:YES];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"ya" ofType:@"wav"];
        if (path) {
            //注册声音到系统
            AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:path]),&shake_sound_male_id);
            AudioServicesPlaySystemSound(shake_sound_male_id);
            //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
        }
        
        AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
        
        //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
    }
}

#pragma mark - 空白处点击
- (IBAction)button:(id)sender {
    doneButton.hidden = YES;
    [self.content resignFirstResponder];
    [self.ShowTime resignFirstResponder];
}

#pragma mark - “设置”按钮点击
- (IBAction)setting:(id)sender {
    if (setUpStr == 0) {
        timePicker.hidden = NO;
        [self.set setTitle:@"完成" forState:UIControlStateNormal];
        setUpStr =1;
    }else{
    timePicker.hidden = YES;
        [self.set setTitle:@"设置" forState:UIControlStateNormal];
        setUpStr =0;
    }
}
@end
